import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/open_live_good_event.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/stream/dialog/calculate_valuation_dialog.dart';
import 'package:star_author/views/stream/dialog/last_backflow_good_info.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/image_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../../../provider/config.dart';
import '../model/live_good_list_entity.dart';

class SelectEvaluateDialog extends StatefulWidget {
  LiveGoodListData data;
  Map select_reference;
  String searchText;
  Map studioDetail;
  late RtcEngine? engine;
  Function? muteCallBack;
  SelectEvaluateDialog({
    Key? key,
    required this.select_reference,
    required this.searchText,
    required this.studioDetail,
    required this.engine,
    required this.muteCallBack,
    required this.data,
  }) : super(key: key);

  @override
  State<SelectEvaluateDialog> createState() => _SelectEvaluateDialogState();
}

class _SelectEvaluateDialogState extends State<SelectEvaluateDialog> {
  int referenceIndex = -1;

  Map select_reference = {};

  List get evaluate_price_range {
    return Provider.of<ConfigProvider>(Get.context!, listen: false)
            .get("settings")?['evaluate_price_range'] ??
        [];
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.select_reference.isNotEmpty) {
      setState(() {
        select_reference = widget.select_reference;
        int indexWhere = evaluate_price_range
            .indexWhere((element) => element == select_reference);
        referenceIndex = indexWhere;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      width: Get.width,
      constraints: BoxConstraints(
        minHeight: 100.w,
        maxHeight: 600.w,
      ),
      child: SafeArea(
        child: Stack(
          children: [
            Positioned(
              child: GestureDetector(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: RoucesUtil.getAssetsIcon('lt_common/clear', 14.w),
                  padding: EdgeInsets.only(
                    left: 12.w,
                    right: 12.w,
                    top: 14.w,
                  ),
                ),
                onTap: () {
                  Get.back();
                },
                behavior: HitTestBehavior.opaque,
              ),
              top: 0.w,
              right: 0.w,
            ),
            Container(
              margin: EdgeInsets.only(
                left: 12.w,
                right: 12.w,
                top: 20.w,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Center(
                    child: Text(
                      "选择估价",
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: rgba(51, 51, 51, 1),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 18.w,
                  ),
                  Container(
                    child: Row(
                      children: [
                        ClipRRect(
                          child: ImageWithPlaceHolder(
                            cover: widget.data.goods?.cover?.url ?? "",
                            width: 128.w,
                            height: 128.w,
                            radius: 4.w,
                          ),
                          borderRadius: BorderRadius.circular(
                            4.w,
                          ),
                        ),
                        SizedBox(
                          width: 10.w,
                        ),
                        Expanded(
                          child: Container(
                            height: 128.w,
                            child: buildContent(),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 20.w,
                  ),
                  //请选择估价
                  Container(
                    height: 48.w,
                    alignment: Alignment.center,
                    width: Get.width,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.w),
                      border: Border.all(
                        width: 1.w,
                        color: rgba(153, 153, 153, 1),
                      ),
                    ),
                    child: referenceIndex == -1
                        ? Text(
                            "请选择估价",
                            style: TextStyle(
                              fontSize: 18.sp,
                              color: rgba(153, 153, 153, 1),
                            ),
                          )
                        : Text(
                            getPriceWithList(
                              select_reference['price_range'] ?? [],
                              intl: true,
                            ),
                            style: TextStyle(
                              fontSize: 18.sp,
                              color: rgba(51, 51, 51, 1),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                  ),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 10.w,
                        bottom: 30.w,
                      ),
                      constraints: BoxConstraints(
                        maxHeight: 300.w,
                      ),
                      child: GridView.builder(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          //设置列数
                          crossAxisCount: 4,
                          //设置横向间距
                          crossAxisSpacing: 10,
                          //设置主轴间距
                          mainAxisSpacing: 10,
                          childAspectRatio: 80 / 32,
                        ),
                        scrollDirection: Axis.vertical,
                        itemCount: evaluate_price_range.length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            child: Container(
                              child: Center(
                                child: Text(
                                  "${evaluate_price_range[index]['name'] ?? ""}",
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: referenceIndex == index
                                        ? rgba(240, 69, 41, 1)
                                        : rgba(51, 51, 51, 1),
                                  ),
                                ),
                              ),
                              width: 80.w,
                              height: 32.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.w),
                                color: referenceIndex == index
                                    ? rgba(255, 240, 237, 1)
                                    : rgba(245, 245, 245, 1),
                                border: Border.all(
                                  width: 1,
                                  color: referenceIndex == index
                                      ? rgba(240, 69, 41, 1)
                                      : Colors.transparent,
                                ),
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                referenceIndex = index;
                                select_reference = evaluate_price_range[index];
                              });
                            },
                          );
                        },
                      ),
                    ),
                  ),
                  buildButton(),
                  SizedBox(
                    height: 20.w,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildButton() {
    return ButtonWidget(
      child: Text(
        "确定",
        style: TextStyle(
          fontSize: 16.sp,
          color: rgba(51, 51, 51, 1),
          fontWeight: FontWeight.w500,
        ),
      ),
      type: ButtonType.bgOrange,
      enabled: referenceIndex != -1,
      onPressed: () {
        if (referenceIndex == -1) {
          CustomToast.show("请选择估价范围!");
          return;
        }
        HttpUtil.commonRequest(
          Get.context!,
          '/api/v1/backflows/${widget.data.id}/assess',
          method: HttpUtil.MethodPut,
          isLoading: true,
          data: {
            "price_range": select_reference['price_range'],
            "anchor_id": MediaRecorderUtil.anchorId,
          },
          loadingText: '最终估价计算中...',
        ).then((value) {
          if (value.statusCode == 201) {
            CustomToast.show(value.data['msg'] ?? "估价成功");
            Get.back();
            widget.data.priceRange = value.data['price_range'] ?? [];
            widget.data.anchorEvaluationPriceRange =
                select_reference['price_range'];
            Get.dialog(
              CalculateValuationDialog(
                select_reference: select_reference,
                muteCallBack: widget.muteCallBack,
                data: widget.data,
                searchText: '',
                studioDetail: widget.studioDetail,
                engine: widget.engine,
              ),
              barrierDismissible: true, //是否可以通过空白点击
              barrierColor: Colors.black54.withOpacity(0.3),
            ).then((value) {
              if (value == null) {
                widget.data.start_explaining = true;
                GlobalEventBus().bus.fire(OpenLiveGoodEvent([widget.data]));
              }
            });
          }
        });
      },
    );
  }

  buildContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          "${widget.data.goods?.title ?? ""}",
          style: TextStyle(
            fontSize: 14.sp,
            color: rgba(51, 51, 51, 1),
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(
          height: 20.w,
        ),
        if (widget.data.last_history_backflow != null) buildLeftWidget(),
      ],
    );
  }

  buildLeftWidget() {
    //是否转回流 转回流显示转回流
    if (widget.data.last_history_backflow != null) {
      return BackflowGoodWidget(
        param: widget.data.last_history_backflow,
      );
    }
    return Container();
  }
}
